package com.zhongke.common.widget;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.Gravity;

import androidx.appcompat.widget.AppCompatTextView;

/**
 * Author: wpt
 * Time: 2021/10/27
 * @Desc： 解决当TextView宽度够大时，drawableLeft会在最左边，
 * 或者drawableRight在最右边的情况,目前不支持同时设置drawableLeft和drawableRight
 */
public class ZKRightLeftDrawableCenterTextView extends AppCompatTextView {

    private  Drawable[] drawables;
    private  Drawable drawable;
    private boolean isRight;

    public ZKRightLeftDrawableCenterTextView(Context context) {
        this(context, null);
    }

    public ZKRightLeftDrawableCenterTextView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public ZKRightLeftDrawableCenterTextView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        drawables = getCompoundDrawables();
        isRight = (drawables[2] != null);
        drawable = drawables[isRight ? 2 : 0];
        setGravity(Gravity.CENTER | (isRight ? Gravity.RIGHT : Gravity.LEFT));
    }

    @Override
    protected void onDraw(Canvas canvas) {
        if (drawable != null) {
            float textWidth = getPaint().measureText(getText().toString());
            int drawablePadding = getCompoundDrawablePadding();
            int drawableWidth = drawable.getMinimumWidth();
            float bodyWidth = textWidth + drawableWidth + drawablePadding + getPaddingLeft() + getPaddingRight();
            float x = isRight ? (bodyWidth - getWidth()) / 2 : (getWidth() - bodyWidth) / 2;
            canvas.translate(x, 0);
        }
        super.onDraw(canvas);
    }
}
